﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LightCAD.Model
{
    public static class TextureManager 
    {
        private static ConcurrentDictionary<string, Texture> textures = new ConcurrentDictionary<string, Texture>();
        private static TextureLoader textureLoader = new TextureLoader();
        public static Texture GetTexture(string path) 
        {
            return textures.GetOrAdd(path,p=> 
            {
                var t=textureLoader.load(p);
                t.wrapS = MathLib.Constants.RepeatWrapping;
                t.wrapT = MathLib.Constants.RepeatWrapping;
                t.repeat=new Vector2(0.0005,0.0005);
                return t; 
            });
        }
    }
    public static class RenderMaterialManager
    {
        private static ConcurrentDictionary<int, int> lcMaterialRenderMap=new ConcurrentDictionary<int, int>();
        private static RenderMaterialCollection renderMaterials = new RenderMaterialCollection();
        public static Material GetRenderMaterial(string uuid) 
        {
            var mat = MaterialManager.GetMaterial(uuid);
            var renderId= lcMaterialRenderMap.GetOrAdd(mat.HashCode, (hc) =>
            {
                var renderMat = new MeshPhysicalMaterial() {color=mat.Color,opacity=mat.Opcity,transparent=mat.Opcity<1,metalness=mat.Metalness,roughness=mat.Roughness,shininess=mat.Shininess,specularColor=mat.Specular};
                if(!string.IsNullOrEmpty( mat.Texture)&&File.Exists(mat.Texture))
                    renderMat.map=TextureManager.GetTexture(mat.Texture);
                renderMaterials.Add(renderMat);
                return renderMat.id;
            });
            return renderMaterials[renderId];
        }
    }
    
    public class RenderMaterialCollection :KeyedCollection<int,Material>
    {

        protected override int GetKeyForItem(Material item)
        {
            return  item.id;
        }
    }
}
